package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * @Author xuejiao
 * Data 2025/5/30 10:33
 */
public class Utils {
    public static WebDriver driver;
    public static WebDriver createDriver() {
        if(driver == null ) {
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            //允许访问所有链接
            options.addArguments("--remote-allow-origins=*");

            driver = new ChromeDriver(options);

            //隐式等待--所有的查找元素都会等待2秒
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        }
        return driver;
    }

    public Utils(String url) {
        //调用driver对象
        driver = createDriver();

        //访问url
        driver.get(url);

    }

    public Utils() {
        //调用driver对象
        driver = createDriver();

    }

    public void handleAlertIfPresent(WebDriverWait wait) {
        try {
            Alert alert = wait.until(ExpectedConditions.alertIsPresent());
            System.out.println("检测到弹窗：" + alert.getText());
            alert.accept();
            Thread.sleep(5000); // 等待 alert 消失，避免残留影响下个页面
        } catch (Exception e) {
            System.out.println("未检测到 alert 弹窗！");
        }
    }

    public void handleAlertIfExists() {
        try {
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
            Alert alert = driver.switchTo().alert();
            System.out.println("检测到残留弹窗：" + alert.getText());
            alert.accept();
            Thread.sleep(1000); // 等待弹窗处理完再执行后续代码
        } catch (NoAlertPresentException ignored) {
            // 没弹窗就跳过
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }






    public void getScreenShot(String str) throws IOException {
        // ./src/test/image/
        //                  /2025/5/26/
        //                             /test01-082139.png
        //                             /test02-122139.png
        //                  /2025/5/27/
        //                             /test01-082139.png
        //                             /test02-122139.png
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        String fileName = "./src/test/image/" + dirTime + "/" + str + "-" + fileTime + ".png";
         File screenshotAs = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        //screenshotAs放到指定位置
        FileUtils.copyFile(screenshotAs,new File(fileName));

    }

    public void handleAllAlertsAndWaitForLogin(WebDriver driver) {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
        // 处理所有 alert 弹窗
        for (int i = 0; i < 5; i++) {
            try {
                Alert alert = wait.until(ExpectedConditions.alertIsPresent());
                System.out.println("检测到弹窗：" + alert.getText());
                alert.accept();
                Thread.sleep(300);
            } catch (TimeoutException e) {
                break; // 没有更多 alert
            } catch (Exception e) {
                System.out.println("处理 alert 出错：" + e.getMessage());
                break;
            }
        }

        // 尝试等待跳转到登录页
        try {
            wait.until(ExpectedConditions.or(
                    ExpectedConditions.titleContains("登录"),
                    ExpectedConditions.urlContains("login"),
                    ExpectedConditions.titleContains("管理员登录页面")
            ));
            System.out.println("当前页面标题：" + driver.getTitle());
        } catch (TimeoutException e) {
            System.out.println(" 跳转未检测到登录页面，当前标题：" + driver.getTitle());
        }
    }



}
